package com.situ.hospital.service.impl;

import com.situ.hospital.dao.IMedicineDAO;
import com.situ.hospital.dao.IOrderDAO;
import com.situ.hospital.dao.Impl.MedicineDAOImpl;
import com.situ.hospital.dao.Impl.OrderDAOImpl;
import com.situ.hospital.pojo.Medicine;
import com.situ.hospital.pojo.Order;
import com.situ.hospital.pojo.query.OrderQuery;
import com.situ.hospital.pojo.vo.OrderVO;
import com.situ.hospital.service.IOrderService;
import com.situ.hospital.util.PageResult;

import java.util.List;

public class OrderServiceImpl implements IOrderService {

    private IOrderDAO orderDAO = new OrderDAOImpl();
    private IMedicineDAO medicineDAO = new MedicineDAOImpl();

    @Override
    public PageResult<OrderVO> selectByPage(OrderQuery orderQuery) {
        List<OrderVO> list = orderDAO.selectByPage(orderQuery);
        int totalCount = orderDAO.selectTotalCount(orderQuery);
        return new PageResult<>(0, "", totalCount, list);
    }

    @Override
    public void deleteById(int id) {
        Order order = orderDAO.selectById(id);
        Medicine medicine = medicineDAO.selectById(order.getMedicineId());
        int inventory = medicine.getInventory() + order.getNumber();
        medicineDAO.updateInventory(order.getMedicineId(), inventory);
        orderDAO.deleteById(id);
    }

    @Override
    public void deleteAll(String[] ids) {
        for(String id : ids) {
            Order order = orderDAO.selectById(Integer.parseInt(id));
            Medicine medicine = medicineDAO.selectById(order.getMedicineId());
            int inventory = medicine.getInventory() + order.getNumber();
            medicineDAO.updateInventory(order.getMedicineId(), inventory);
            orderDAO.deleteById(Integer.parseInt(id));
        }
    }

    @Override
    public void add(Order order) {
        orderDAO.add(order);
        Medicine medicine = medicineDAO.selectById(order.getMedicineId());
        int inventory = medicine.getInventory() - order.getNumber();
        medicineDAO.updateInventory(order.getMedicineId(), inventory);
    }

    @Override
    public Order selectById(int id) {
        return orderDAO.selectById(id);
    }

    @Override
    public void update(Order order) {
        Order oldOrder = orderDAO.selectById(order.getId());
        Medicine oldMedicine = medicineDAO.selectById(oldOrder.getMedicineId());
        int oldInventory = oldMedicine.getInventory() + oldOrder.getNumber();
        medicineDAO.updateInventory(oldMedicine.getId(), oldInventory);
        Medicine newMedicine = medicineDAO.selectById(oldOrder.getMedicineId());
        int newInventory = newMedicine.getInventory() - order.getNumber();
        medicineDAO.updateInventory(newMedicine.getId(), newInventory);
        orderDAO.update(order);
    }
}
